class LZText {
  toRotate: string
  el: any
  loopNum: number
  period: number
  txt: string
  isDeleting: boolean
  constructor(el: any, toRotate: string, period: number) {
    this.toRotate = toRotate
    this.el = el
    this.loopNum = 0
    this.period = period || 2000
    this.txt = ''
    this.isDeleting = false
  }
  tick() {
    const i = this.loopNum % this.toRotate.length
    const fullTxt = this.toRotate[i]

    if (this.isDeleting) {
      this.txt = fullTxt.substring(0, this.txt.length - 1)
    } else {
      this.txt = fullTxt.substring(0, this.txt.length + 1)
    }

    this.el.innerHTML = '<span class="wrap">' + this.txt + '</span>'

    let delta = 200 - Math.random() * 100

    if (this.isDeleting) {
      delta /= 2
    }

    if (!this.isDeleting && this.txt === fullTxt) {
      delta = this.period
      this.isDeleting = true
    } else if (this.isDeleting && this.txt === '') {
      this.isDeleting = false
      this.loopNum++
      delta = 500
    }

    setTimeout(() => {
      this.tick()
    }, delta)
  }
}

const txtAni = function (txt_class: string) {
  const elements = document.getElementsByClassName(txt_class)
  console.log(elements.length)
  for (let i = 0; i < elements.length; i++) {
    const toRotate = elements[i].getAttribute('data-type')
    if (toRotate) {
      const lzText = new LZText(elements[i], JSON.parse(toRotate), 2000)
      lzText.tick()
    }
  }
  // INJECT CSS
  const css = document.createElement('style')
  css.type = 'text/css'
  css.innerHTML = '.typewrite > .wrap { border-right: 0.08em solid #fff }'
  document.body.appendChild(css)
}

export default txtAni

// 使用时直接导入在mounted里面调用即可
// import txtAni from '@/utils/text-type.ts'

// onMounted(() => {
//   txtAni('typewrite')
//   txtAni('test')
// })
